const axios = require("axios").default.create({
  headers: {
    "User-Agent": "duapp/3.5.4(android;6.0.1)"
  }
});
const qs = require("querystring")
const FormData = require("form-data");
const rn = require("random-number");
const util = require("util");
const setCookieParser = require("set-cookie-parser");
const CommonAxHandler = require("../CommonAxerrHandler");
const jsB64 = require("js-base64").Base64;
const du_app_key = jsB64.encode("du_app:login_string:qiniu", true);


/**@type {{loginToken:String,duToken_in_cookie:String,duimei:String,duuuid:String}} */
let cache_login_configs = null;

/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{loginToken:String,duToken_in_cookie:String,duimei:String,duuuid:String}}>}
 */
function get_a_new_login_string() {
  return new Promise(resolve => {
    let duimei = `8677870360752${parseInt(rn({ min: 29, max: 50 }))}`;/////'867787036075244'
    const duuuid = '8282c48b1b424985'
    axios.post("https://m.poizon.com/users/unionLogin?newSign=b5d99bbb9629ecca57efa3378ff636a4",
      qs.stringify({
        userName: '18390921465',
        password: '276a2110b9c1da3483f22e2e87b458fb',
        type: 'pwd',
        sourcePage: "",
        countryCode: 86,
        sign: "27aa34a05250e99fe2e933d56df26b7d"
      }), {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          duchannel: 'xiaomi',
          dudeviceTrait: 'Redmi Note 4X',
          duimei: duimei,
          duplatform: 'android',
          duuuid: duuuid,
          duv: '3.5.4'
        },
        validateStatus: s => s == 200
      }).then(axresp => {
        if (axresp.data.status && axresp.data.status == 200
          && axresp.data.data
          && axresp.data.data.loginInfo
          && axresp.data.data.loginInfo.loginToken
          && axresp.headers["set-cookie"]
          && axresp.headers["set-cookie"][0]
          && axresp.headers["set-cookie"][0].startsWith("duToken")) {
          let loginToken = axresp.data.data.loginInfo.loginToken;
          let parsed = setCookieParser(axresp.headers["set-cookie"][0]);
          if (parsed[0] && parsed[0].value) {
            let cookie_dutoken_value = parsed[0].value;
            // debugger
            return resolve({
              ok: true,
              msg: "ok",
              data: {
                loginToken: loginToken,
                duToken_in_cookie: cookie_dutoken_value,
                duimei: duimei,
                duuuid: duuuid
              }
            })
          }
        }
        throw new Error(`not sanity axresp,headers is [${util.inspect(axresp.headers)}],response is [${util.inspect(axresp.data)}]`)
      }).catch(axerr => {
        CommonAxHandler(resolve)(axerr);
      })
  })
}

/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{uptoken:String}}>}
 * @param {{loginToken:String,duToken_in_cookie:String,duimei:String,duuuid:String}} configs 
 */
function verifyLoginString(configs) {
  return new Promise(resolve => {
    axios.get('https://m.poizon.com/client/qiNiuToken?sign=16eebc0564541aa4b1e615280d50c9c3&newSign=1e71a1c6060d4d74da89db198b3ff6b0', {
      headers: {
        Connection: 'Keep-Alive',
        'Accept-Encoding': 'gzip',
        Cookie: `duToken=${encodeURIComponent(configs.duToken_in_cookie)}`,
        duloginToken: configs.loginToken,
        "duuuid": configs.duuuid,
        "duimei": configs.duimei,
        "duv": "3.5.4",
        duplatform: 'android',
        duchannel: 'xiaomi',
        dudeviceTrait: 'Redmi Note 4X'
      },
      validateStatus: s => s == 200
    }).then(axresp => {
      if (axresp.data && axresp.data.status == 200
        && axresp.data.data
        && axresp.data.data.qiNiuToken) {
        return resolve({
          ok: true,
          msg: "ok",
          data: {
            uptoken: axresp.data.data.qiNiuToken
          }
        })
      }
      throw new Error(`NO sanity axresp:${util.inspect(axresp.data)}`)
    }).catch(axerr => {
      CommonAxHandler(resolve)(axerr);
    })
  })
}


/**
 * @returns {Promise<{ok:Boolean,msg:String,data:{uptoken:String}}>}
 */
function get_token() {
  return new Promise(async resolve => {
    if (cache_login_configs) {
      let o_try = await verifyLoginString(cache_login_configs);
      if (o_try.ok) {
        return resolve({
          ok: true,
          msg: "ok",
          data: {
            uptoken: o_try.data.uptoken
          }
        })
      } else {
        cache_login_configs = null;
      }
    }
    let o_getLoginString = await get_a_new_login_string();
    if (!o_getLoginString.ok) {
      return resolve({
        ok: false,
        msg: `failed to get a new login string:${o_getLoginString.msg}`
      })
    }
    let o_v = await verifyLoginString(o_getLoginString.data);
    if (!o_v.ok) {
      return resolve({
        ok: false,
        msg: `the new login string can NOT pass the test:${o_v.msg}`
      })
    }
    cache_login_configs = o_getLoginString.data;
    resolve({
      ok: true,
      msg: "ok",
      data: {
        uptoken: o_v.data.uptoken
      }
    })
  })
}



module.exports = {
  "__debug": {
    get_a_new_login_string: get_a_new_login_string,
    verifyLoginString: verifyLoginString,
  },
  get_token: get_token
}